package com.springexample.demo.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * @Author XuDon
 * @ClassName BeanUtils.java
 * @Description TODO
 * @Date 2022年04月21日 14:40:00
 **/
@Slf4j
@Component
public class BeanUtils {
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 取消注册
     */
    public boolean unRegisterBean(String beanName){
        Object targetBean = getBeanFactory().getBean(beanName);
        DefaultListableBeanFactory beanFactory = getBeanFactory();
        if(!beanFactory.containsBeanDefinition(beanName)){
            log.info("未找到指定bean:"+beanName);
            return false;
        }
        log.info("找到指定bean:"+beanName);
        beanFactory.destroySingleton(beanName);
        beanFactory.removeBeanDefinition(beanName);
        log.info("已注销指定bean:"+beanName);
        return true;
    }

    /**
     * 获取beanFactory
     * @return
     */
    private DefaultListableBeanFactory getBeanFactory(){
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        return (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
    }
}
